package pl.olsson.plugin.script;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import javax.script.SimpleScriptContext;

/**
 *
 * @author nilols
 */
public class Context extends SimpleScriptContext {

    private File directory;
    private ProxyWriter proxyWriter;
    private ProxyReader proxyReader;
    private ProxyWriter proxyErrorWriter;

    public Context(File directory) {
        this.directory = directory;
        this.proxyWriter = new ProxyWriter(getWriter());
        this.proxyReader = new ProxyReader(getReader());
        this.proxyErrorWriter = new ProxyWriter(getErrorWriter());
        this.setWriter(proxyWriter);
        this.setReader(proxyReader);
        this.setErrorWriter(proxyErrorWriter);
    }

    public void setOutputFile(String name) {
        try {
            File file = new File(directory, name);
            file.getParentFile().mkdirs();
            proxyWriter.setWriter(new PrintWriter(new FileWriter(file, true)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void closeOutputFile() {
        
    }

    public void setInputFile(String name) {
        File file = new File(directory, name);
        try {
            proxyReader.setReader(new FileReader(file));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void closeInputFile() {

    }

    public void setErrorFile(String name) {
        try {
            File file = new File(directory, name);
            file.getParentFile().mkdirs();
            proxyErrorWriter.setWriter(new PrintWriter(new FileWriter(file, true)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void closeErrorFile() {
        proxyErrorWriter.close();
    }
}
